package lxs.tool.liberator.system.config;


import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;

import lxs.tool.liberator.common.utils.SpringContextUtil;
import lxs.tool.liberator.work.pojo.Project;
import org.springframework.beans.factory.annotation.Value;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.StaticApplicationContext;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.stereotype.Component;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;


import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;

//@Component
public class DynamicDataSource extends AbstractRoutingDataSource {
    @Value("${spring.datasource.druid.driver-class-name}")
    private String driver;
    @Value("${spring.datasource.druid.url}")
    private String url;
    @Value("${spring.datasource.druid.username}")
    private String username;
    @Value("${spring.datasource.druid.password}")
    private String password;
    private static final String urlFrame = "jdbc:{db-type}://{db-ip}:{host}/{dbname}?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai";

    public static Map<Object, Object> dataSourcesMap = new HashMap<>();
    public static Map<String, Statement> statementMap = new HashMap<>();



    @Override
    protected Object determineCurrentLookupKey() {
        return DbHolder.get();
    }

    @Override
    protected DataSource determineTargetDataSource() {
        return super.determineTargetDataSource();
    }

    public void switchSource(String dataSource) {
        DbHolder.set(dataSource);
        this.afterPropertiesSet();
    }

    public void addDataSource(String key, DataSource dataSource) {
        dataSourcesMap.put(key, dataSource);
    }

    public void removeDataSource(String key) {
        dataSourcesMap.remove(key);
        statementMap.remove(key);
    }

    // 调用此方法，切换数据源
    public void switchTo(Project project) throws SQLException {
        if (!DynamicDataSource.dataSourcesMap.containsKey(project.getId())) {
            String u = urlFrame;
            u = u.replace("{db-type}", project.getDbType());
            u = u.replace("{db-ip}", project.getDbIp());
            u = u.replace("{host}", project.getDbHost());
            u = u.replace("{dbname}", project.getDbname());
            DruidDataSource dataSource = new DruidDataSource();
            dataSource.setUrl(u);
            dataSource.setUsername(project.getDbUsername());
            dataSource.setPassword(project.getDbPassword());
            dataSource.setDriverClassName(driver);
            this.addDataSource(project.getId(), dataSource);
            statementMap.put(project.getId(), dataSource.getConnection().createStatement());
        }
        DbHolder.set(project.getId());
        System.out.println(DbHolder.get());
    }


    public void clear() {
        DbHolder.remove();
        this.afterPropertiesSet();
    }

    public void switchBack() {
        this.clear();
    }


    public void execute(String sql) throws SQLException {

        statementMap.get(DbHolder.get()).execute(sql);
    }

    public ResultSet executeQuery(String sql) throws SQLException {

        return statementMap.get(DbHolder.get()).executeQuery(sql);

    }
}
